<?php
namespace app\admin\small;

use app\common\Small;

class Tree extends Small {
    function zTree($assign){
        $catelog = model('DocCatelog')->where([['doc_id','=',$assign['doc_id']]])->order('sort desc')->select()->toArray();
        $assign['catelog'] = $this->_zTreeFormatData($catelog);
        $this->assign($assign);
        return $this->fetch();
    }

    function _zTreeFormatData($data)
    {
        foreach($data as $k=>$v)
        {
            $data[$k]['pId'] = $data[$k]['pid'];
            if( $data[$k]['pId'] == 0 ){
                $data[$k]['childOuter'] = false;
            }
        }
        $root = ['id'=>0,'name'=>'所有目录','pid'=>-1,'pId'=>-1,'doc_id'=>0,'sort'=>0,'childOuter'=>false];
        $data[] = $root;
        return json_encode($data);
    }

    function index($assign)
    {
        $catelog = model('DocCatelog')->where([['doc_id','=',$assign['doc_id']]])->select()->toArray();
        $assign['catelog'] = $this->_indexFormatData($catelog);
        $this->assign($assign);
        return $this->fetch();
    }

    function _indexFormatData($data){
        $return = [];
        $top_categories = [];
        foreach( $data as $item )
        {
            if( $item['pid'] == 0 )
            {
                $top_categories[] = $item;
            }
        }
        foreach( $top_categories as $k=>$item )
        {
            $return[$k]['title'] = $item['name'];
            $return[$k]['type'] = 'folder';
            foreach( $data as $val )
            {
                if( $item['id'] == $val['pid'] )
                {
                    $tempVal['title'] = $val['name'];
                    $tempVal['type'] = 'item';
                    $return[$k]['children'][] = $tempVal;
                }
            }
            if( !isset($return[$k]['children']) )
            {
                $return[$k]['children'] = [];
            }
        }
        return json_encode( $return );
    }
}